"""
通知系统视图
"""
from django.utils import timezone
from django.db.models import Q
from rest_framework import generics, status, viewsets
from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination
from accounts.permissions import IsTeacherOrAdmin
from accounts.models import User
from .models import Notification, NotificationTemplate, NotificationSettings
from .serializers import (
    NotificationSerializer,
    NotificationTemplateSerializer,
    NotificationSettingsSerializer,
    SendNotificationSerializer,
    BulkNotificationSerializer
)


class NotificationPagination(PageNumberPagination):
    """通知分页"""
    page_size = 20
    page_size_query_param = 'page_size'
    max_page_size = 100


class NotificationViewSet(viewsets.ModelViewSet):
    """通知管理ViewSet"""
    serializer_class = NotificationSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = NotificationPagination

    def get_queryset(self):
        """获取当前用户的通知"""
        queryset = Notification.objects.filter(recipient=self.request.user).order_by('-created_at')

        # 筛选条件
        notification_type = self.request.query_params.get('type', None)
        if notification_type:
            queryset = queryset.filter(notification_type=notification_type)

        is_read = self.request.query_params.get('is_read', None)
        if is_read is not None:
            queryset = queryset.filter(is_read=is_read.lower() == 'true')

        priority = self.request.query_params.get('priority', None)
        if priority:
            queryset = queryset.filter(priority=priority)

        return queryset

    @action(detail=True, methods=['post'])
    def mark_read(self, request, pk=None):
        """标记单个通知为已读"""
        notification = self.get_object()
        if not notification.is_read:
            notification.is_read = True
            notification.read_at = timezone.now()
            notification.save()
        return Response({'message': '已标记为已读'})

    @action(detail=False, methods=['post'])
    def mark_all_read(self, request):
        """标记所有通知为已读"""
        updated_count = Notification.objects.filter(
            recipient=request.user,
            is_read=False
        ).update(
            is_read=True,
            read_at=timezone.now()
        )
        return Response({'message': f'已标记 {updated_count} 条通知为已读'})

    @action(detail=False, methods=['get'])
    def unread_count(self, request):
        """获取未读通知数量"""
        count = Notification.objects.filter(
            recipient=request.user,
            is_read=False
        ).count()
        return Response({'count': count})


class NotificationTemplateViewSet(viewsets.ModelViewSet):
    """通知模板管理"""
    queryset = NotificationTemplate.objects.all()
    serializer_class = NotificationTemplateSerializer
    permission_classes = [IsTeacherOrAdmin]

    def get_queryset(self):
        queryset = NotificationTemplate.objects.filter(is_active=True).order_by('notification_type', 'name')

        notification_type = self.request.query_params.get('type', None)
        if notification_type:
            queryset = queryset.filter(notification_type=notification_type)

        return queryset


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def send_notification(request):
    """发送单个通知"""
    serializer = SendNotificationSerializer(data=request.data)
    if serializer.is_valid():
        try:
            # 获取接收人
            recipient_id = serializer.validated_data['recipient_id']
            recipient = User.objects.get(id=recipient_id)

            # 创建通知
            notification = Notification.objects.create(
                recipient=recipient,
                sender=request.user,
                notification_type=serializer.validated_data['notification_type'],
                title=serializer.validated_data['title'],
                content=serializer.validated_data['content'],
                priority=serializer.validated_data.get('priority', 'normal'),
                is_sent=True,
                sent_at=timezone.now()
            )

            return Response({
                'message': '通知发送成功',
                'notification_id': notification.id
            }, status=status.HTTP_201_CREATED)

        except User.DoesNotExist:
            return Response({'error': '接收人不存在'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['POST'])
@permission_classes([IsTeacherOrAdmin])
def send_bulk_notification(request):
    """批量发送通知"""
    serializer = BulkNotificationSerializer(data=request.data)
    if serializer.is_valid():
        try:
            recipient_ids = serializer.validated_data['recipient_ids']
            recipients = User.objects.filter(id__in=recipient_ids)

            if not recipients.exists():
                return Response({'error': '没有找到有效的接收人'}, status=status.HTTP_400_BAD_REQUEST)

            # 批量创建通知
            notifications = []
            for recipient in recipients:
                notifications.append(Notification(
                    recipient=recipient,
                    sender=request.user,
                    notification_type=serializer.validated_data['notification_type'],
                    title=serializer.validated_data['title'],
                    content=serializer.validated_data['content'],
                    priority=serializer.validated_data.get('priority', 'normal'),
                    is_sent=True,
                    sent_at=timezone.now()
                ))

            created_notifications = Notification.objects.bulk_create(notifications)

            return Response({
                'message': f'成功发送 {len(created_notifications)} 条通知',
                'sent_count': len(created_notifications)
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsTeacherOrAdmin])
def get_users_for_notification(request):
    """获取可发送通知的用户列表"""
    from .serializers import UserSimpleSerializer

    # 根据当前用户角色过滤用户
    if request.user.role == 'admin':
        # 管理员可以给所有人发送通知
        users = User.objects.filter(is_active=True).order_by('role', 'username')
    elif request.user.role == 'teacher':
        # 老师可以给学生发送通知
        users = User.objects.filter(is_active=True, role='student').order_by('username')
    else:
        # 其他角色不能发送通知
        return Response({'error': '没有权限发送通知'}, status=status.HTTP_403_FORBIDDEN)

    # 支持搜索
    search = request.query_params.get('search', None)
    if search:
        users = users.filter(
            Q(username__icontains=search) |
            Q(first_name__icontains=search) |
            Q(last_name__icontains=search) |
            Q(email__icontains=search)
        )

    # 支持角色过滤
    role = request.query_params.get('role', None)
    if role:
        users = users.filter(role=role)

    serializer = UserSimpleSerializer(users, many=True)
    return Response(serializer.data)
